package word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.lang.reflect.Field;
import java.io.*;
import java.util.*;

/**
 * OfficeUtils : Office工具类
 *
 * @author zyw
 * @create 2024-06-24  16:35
 */

public class OfficeUtils {

    /**
     * 对象转Map
     * @param obj
     * @return
     */
    public static Map<String, String> objectToMap(Object obj) {
        Map<String, String> map = new HashMap<>();
        Class<?> clazz = obj.getClass();

        // 获取类中所有声明的字段（包括私有、受保护、默认、公共）
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true); // 设置字段可访问（如果是私有的）

            try {
                Object value = field.get(obj);
                String key = "${" + field.getName() + "}"; // 构造key，以${name}形式
                map.put(key, String.valueOf(value));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return map;
    }

    /**
     * 段落文本填充
     *
     * @param document 文档
     * @param insertTextMap 填充内容
     */
    public static void paragraphTextFilling(XWPFDocument document, Map<String, String> insertTextMap) {
        Set<String> set = insertTextMap.keySet();

        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
        while (itPara.hasNext()) {
            // 获取文档中当前的段落文字信息
            XWPFParagraph paragraph = itPara.next();
            List<XWPFRun> run = paragraph.getRuns();
            // 遍历段落文字对象
            for (int i = 0; i < run.size(); i++) {
                // 获取段落对象
                if (run.get(i) == null) {    //段落为空跳过
                    continue;
                }
                String sectionItem = null;
                try {
                    // 检查段落中是否包含文本框
                    sectionItem = run.get(i).getText(run.get(i).getTextPosition());    //段落内容
                } catch (Exception e) {
                }
                if (sectionItem == null) {
                    continue;
                }
                // 遍历自定义表单关键字，替换Word文档中的内容
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    // 当前关键字
                    String key = iterator.next();
                    // 替换内容
                    sectionItem = sectionItem.replace(key, String.valueOf(insertTextMap.get(key)));
                }
                run.get(i).setText(sectionItem, 0);
            }
        }
    }


    /**
     * word转InputStream
     *
     * @param document
     * @return
     */
    public static InputStream writeDocumentToInputStream(XWPFDocument document) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);
            byteArrayOutputStream.close();
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

